const Router = require('koa-router')
const db = require('../db')
const config = require('../config')

const router = new Router({ prefix: '/api/mall' })

// 获取商品列表
router.get('/products', async (ctx) => {
  try {
    const products = await db.query('SELECT * FROM mall_products')
    
    // 处理图片路径
    const processedProducts = products.map(product => ({
      ...product,
      image: product.image.startsWith('http') 
        ? product.image 
        : `${config.development.baseURL}${product.image}`
    }))

    ctx.body = { code: 200, data: processedProducts }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 兑换商品
router.post('/exchange', async (ctx) => {
  const { productId, userId } = ctx.request.body
  // 使用请求中的用户ID，如果未提供则默认为1（用于开发测试）
  const userIdToUse = userId || 1;

  try {
    // 获取商品信息
    const products = await db.query('SELECT * FROM mall_products WHERE id = ?', [productId])
    const product = products[0]
    if (!product || product.stock <= 0) {
      throw new Error('商品已售罄')
    }

    // 检查积分是否足够
    const earnRows = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "earn"',
      [userIdToUse]
    )
    const spendRows = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "spend"',
      [userIdToUse]
    )
    const availablePoints = Number(earnRows[0]?.total || 0) - Number(spendRows[0]?.total || 0)

    if (availablePoints < product.points) {
      throw new Error('积分不足')
    }

    // 记录积分消费
    await db.query(
      'INSERT INTO points_history (user_id, amount, type, title, created_at) VALUES (?, ?, "spend", ?, NOW())',
      [userIdToUse, product.points, `兑换商品：${product.title}`]
    )

    // 更新商品库存
    await db.query(
      'UPDATE mall_products SET stock = stock - 1 WHERE id = ? AND stock > 0',
      [productId]
    )

    ctx.body = { code: 200, message: '兑换成功' }
  } catch (error) {
    console.error('兑换失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: error.message || '兑换失败' }
  }
})

module.exports = router